from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from airtest.core.api import *
import logging
import re
import subprocess

logging.getLogger("airtest").setLevel(logging.ERROR)
# 创建一个logger
logger = logging.getLogger("抖音")
logger.setLevel(logging.DEBUG)
logging.getLogger("airtest").setLevel(logging.ERROR)
# 创建一个logger
logger = logging.getLogger("抖音")
logger.setLevel(logging.DEBUG)


def get_devices_list():
    """获取所有在线设备

    Returns:
        _type_: 设备列表
    """
    res = subprocess.run("adb devices",
                         capture_output=True,
                         text=True,
                         shell=True)
    # print(res.stdout, res.stderr)
    result = res.stdout
    result = result.splitlines()[1:]

    devices_list = []
    for res in result:
        device = res.split('\t')[0]
        if device != '':
            devices_list.append(device)
    return devices_list


dev = get_devices_list()[0]
print(dev)
dev = connect_device(
    f"android://127.0.0.1:5037/{dev}"  #?cap_method=javacap&touch_method=adb
)

live = True
watching_live = True
wastetime_task_begin = True
wastetime_value = True
dev.wake()
start_app("com.ss.android.ugc.aweme.lite")
poco = AndroidUiautomationPoco(device=dev,
                               use_airtest_input=True,
                               screenshot_each_action=False)

freeze_poco = poco.freeze()
if freeze_poco("com.lynx.tasm.ui.image.FlattenUIImage").exists():
    logger.info("在直播界面")
    if live and watching_live:
        while wastetime_task_begin and wastetime_value:
            freeze_poco = poco.freeze()
            if freeze_poco(text='领金币').exists():
                freeze_poco(text='领金币').click()
            if freeze_poco(text='开宝箱').exists():
                freeze_poco(text='开宝箱').click()
                # while 1:
            if freeze_poco(text='赠送').exists():
                keyevent("back")
            elif freeze_poco(text='去Ta直播间').exists():
                freeze_poco(text='去Ta直播间').click()
            elif freeze_poco(text="还可做任务赚").exists():
                freeze_poco(text="还可做任务赚").click()

            if freeze_poco(textMatches="\d+:\d+后可开").exists():
                wait_time = re.findall(
                    r'\d+',
                    poco(textMatches="\d+:\d+后可开").get_text())
                if len(wait_time) > 1:
                    wait_time = int(wait_time[0]) * 60 + int(wait_time[1])
                else:
                    wait_time = int(wait_time[0])
                logger.info(f"看直播 等待{wait_time}秒")
                # sleep(wait_time + 2)
            # swipe(start_point, end_point)
    else:
        keyevent('back')
    # return True
